package com.zhkj.txg.module.home.ui

import android.app.Activity
import android.content.Intent
import android.view.View
import android.widget.TextView
import androidx.core.view.postDelayed
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.entity.node.BaseNode
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.ScreenUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.home.adapter.SecondBannerAdapter
import com.zhkj.txg.module.home.adapter.SecondProductListAdapter
import com.zhkj.txg.module.home.entity.MarketCateListEntity
import com.zhkj.txg.module.home.popup.MarketTabPopupWindow
import com.zhkj.txg.module.home.vm.MarketViewModel
import com.zhkj.txg.utils.GridItemDecoration
import kotlinx.android.synthetic.main.activity_second_category1.*

class SecondCategory1Activity : ViewModelActivity<MarketViewModel>() {

    companion object {
        private val TYPE_MARKET = 0
        private val TYPE_GOODS = 1
        private val TYPE = "type"
        private val ID = "id"
        fun open(activity: Activity, id: Int) {
            val intent = Intent(activity, SecondCategory1Activity::class.java)
                .putExtra(ID, id).putExtra(TYPE, TYPE_MARKET)
            activity.startActivity(intent)
        }

        fun goodsCate(activity: Activity, id: Int) {
            val intent = Intent(activity, SecondCategory1Activity::class.java)
                .putExtra(ID, id).putExtra(TYPE, TYPE_GOODS)
            activity.startActivity(intent)
        }
    }

    // 所有分类的PopupWindow
    private val popupWindow: MarketTabPopupWindow by lazy {
        MarketTabPopupWindow(
            this, viewModel.marketCateLiveData.value?.response?.data?.category ?: mutableListOf()
        ) { position ->
            if (position == tabCate.selectedTabPosition) return@MarketTabPopupWindow
            tabCate.getTabAt(position)?.select()
            // 滚动商品列表到对应item
            scrollToListPosition(getListAdapterRealPosition(position))
        }
    }
    private val productAdapter = SecondProductListAdapter()
    private val bannerAdapter = SecondBannerAdapter()

    override val layoutResId: Int = R.layout.activity_second_category1
    override fun setViewModel(): MarketViewModel = createViewModel()
    override fun statusTitleBar(): View? = titleSecond

    override fun initUI() {
        // 跳转搜索框
        tvSecondSearch.setOnClickListener {
            if (intent.getIntExtra(TYPE, TYPE_MARKET) == TYPE_MARKET)
                SearchActivity.marketOpen(this, intent.getIntExtra(ID, 0).toLong())
            else SearchActivity.homeOpen(this, intent.getIntExtra(ID, 0).toLong())
        }
        // 弹出所有分类框
        ivSecondCategory.setOnClickListener {
            popupWindow.setSelectedPosition(tabCate.selectedTabPosition).showPopupWindow()
        }
        // 轮播图
        with(bannerSecond) {
            layoutParams.height = (ScreenUtil.getScreenWidth(this@SecondCategory1Activity) * 0.75).toInt()
            adapter = bannerAdapter
        }
        // 商品列表
        with(productList) {
            val gridLayoutManager = GridLayoutManager(context, 3)
            layoutManager = gridLayoutManager
            adapter = productAdapter
            addItemDecoration(GridItemDecoration(ScreenUtil.dip(context, 15), ScreenUtil.dip(context, 15)))
            // 监听滚动到哪一个List
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                var lastFirstPosition = 0
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    val position = gridLayoutManager.findFirstVisibleItemPosition()
                    if (lastFirstPosition != position) {
                        val parentIndex = productAdapter.findParentNode(position)
                        val tabPosition = if (parentIndex < 0) position else parentIndex
                        if (tabPosition != tabCate.selectedTabPosition) {
                            val id = (productAdapter.data[tabPosition] as? MarketCateListEntity)?.id
                            viewModel.marketCateLiveData.value?.response?.data?.list?.let {
                                loop@ for (item in it.withIndex()) {
                                    if (item.value.id == id) {
                                        tabCate.getTabAt(item.index)?.select()
                                        break@loop
                                    }
                                }
                            }
                        }
                        lastFirstPosition = position
                    }
                }
            })
        }
    }

    override fun initViewModel() {
        // 页面数据观察者
        viewModel.marketCateLiveData.observe(this, Observer {
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) it.response?.data?.let { data ->
                // 设置轮播图
                bannerAdapter.setNewData(data.banner)
                // 设置二级分类列表
                for (item in data.category.withIndex()) tabCate.addTab(
                    tabCate.newTab().setCustomView(layoutInflater.inflate(R.layout.item_market_tab, null).apply {
                        findViewById<TextView>(R.id.tvMarketTab).text = item.value.name
                        setOnClickListener {
                            appBar.setExpanded(false)
                            tabCate.stopNestedScroll()
                            tabCate.getTabAt(item.index)?.select()
                            // 滚动商品列表到对应的position
                            scrollToListPosition(getListAdapterRealPosition(item.index))
                        }
                    })
                )
                // 设置商品列表
                productAdapter.setNewData(data.list as MutableList<BaseNode>)
            }
        })
    }

    override fun initData() {
        val catId = intent.getIntExtra(ID, 0)
        val type = intent.getIntExtra(TYPE, TYPE_MARKET)
        if (type == TYPE_MARKET) viewModel.marketCate(AccountManager.getToken(), catId)
        else viewModel.secondCate(AccountManager.getToken(), catId)
    }

    private fun getListAdapterRealPosition(tabIndex: Int): Int {
        val id = viewModel.marketCateLiveData.value?.response?.data?.list?.get(tabIndex)?.id ?: 0
        var realPosition = 0
        for (value in productAdapter.data.withIndex()) {
            if (value.value is MarketCateListEntity && (value.value as MarketCateListEntity).id == id) {
                realPosition = value.index
                break
            }
        }
        return realPosition
    }

    private fun scrollToListPosition(realPosition: Int) {
        // 滚动商品列表到对应item
        productList.scrollToPosition(realPosition)
        // 判断是否滚动到最上面
        productList.postDelayed(200) {
            (productList.layoutManager as GridLayoutManager).let {
                val firstPosition = it.findFirstVisibleItemPosition()
                if (firstPosition < realPosition) {
                    if (realPosition - firstPosition <= it.childCount) {
                        val top = it.getChildAt(realPosition - firstPosition)?.top
                        productList.scrollBy(0, (top ?: 0))
                    }
                } else if ((it.getChildAt(0)?.top ?: 0) > 0) {
                    val top = it.getChildAt(0)?.top
                    productList.scrollBy(0, (top ?: 0))
                }
            }
        }
    }
}